import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import serverConfig from '../config';
import FileEntity from './entity/file.entity';
import FileController from './controller/file.controller';
import FileService from './service/file.service';
import { MulterModule } from '@nestjs/platform-express';
import { NacosModule } from 'libs/nacos/nacos.module';
import nacos from 'config/nacos';
import { NacosNamingClientService } from 'libs/nacos/nacosNamingClient.service';
import AuthInterceptor from './interceptor/auth.interceptor';
import AuthApi from './api/auth.api';
import { NacosConfigClientService } from 'libs/nacos/nacosConfigClient.service';

const nacosModule = NacosModule.forRoot({
  clientOptions: {
    //配置中心
    serverAddr: nacos.url,
    namespace: nacos.namespace,
  },
  nacosNamingClientConfig: {
    //服务注册发现
    logger: console,
    serverList: nacos.url,
    namespace: nacos.namespace,
  },
});

@Module({
  imports: [
    nacosModule,
    TypeOrmModule.forRootAsync({
      useFactory: async (
        nacosConfigClientService: NacosConfigClientService,
      ) => {
        const mySqlConfig = await nacosConfigClientService.getConfig(
          'mysql',
          'DEFAULT_GROUP',
        );
        return {
          type: 'mysql',
          host: mySqlConfig.host,
          port: mySqlConfig.port,
          username: mySqlConfig.username,
          password: mySqlConfig.password,
          database: mySqlConfig.database,
          entities: [FileEntity],
          synchronize: true,
          connectorPackage: 'mysql2',
        };
      },
      imports: [nacosModule],
      inject: [NacosConfigClientService],
    }),
    MulterModule.register({
      dest: serverConfig.dir,
    }),
    TypeOrmModule.forFeature([FileEntity]),
  ],
  controllers: [FileController],
  providers: [FileService, AuthApi, AuthInterceptor],
})
export class MsFileModule {
  constructor(readonly nacosNamingClientService: NacosNamingClientService) {
    //项目启动时注入服务
    nacosNamingClientService.registerInstance({
      serviceName: serverConfig.serviceName,
      groupName: 'DEFAULT_GROUP',
      instance: {
        ip: serverConfig.ip,
        port: serverConfig.port,
        instanceId: serverConfig.serviceId,
        healthy: true,
        enabled: true,
      },
    });
  }
}
